package top.fate.until;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import top.fate.entity.FileData;

import java.io.*;
import java.util.*;


public class FileReading {

    //读取文件夹名称
    public List<FileData> getFileName() {
        String path = "D:/desktop"; // 路径
        File f = new File(path);//获取路径  F:测试目录
        if (!f.exists()) {
          //  System.out.println(path + " 不存在文件夹");//不存在就输出
            return null;
        }

        File fa[] = f.listFiles();//用数组接收  F:笔记总结C#, F:笔记总结if语句.txt
        List<FileData> list = new ArrayList<>();
        for (int i = 0; i < fa.length; i++) {//循环遍历
            File fs = fa[i];//获取数组中的第i个
            FileData fileData = new FileData();
            if (fs.isDirectory()) {
                System.out.println(fs.getName() + " [目录]");//如果是目录就输出
            } else {
                String s = "D:\\desktop\\" + fs.getName();
                String readWord = readWord(s);
                fileData.setName(fs.getName());
                fileData.setReadcon(readWord);
                fileData.setId(UUID.randomUUID().toString());
                list.add(fileData);
              //  System.out.println(fs.getName() + readWord);
            }
        }
        return list;

    }
    //读取文件内容
    public String readWord(String path){
        String buffer = "";
        try {
            if (path.endsWith(".doc")){  //读取文档后缀为.doc
                InputStream is = new FileInputStream(new File(path));
                WordExtractor ex = new WordExtractor(is);
                String[] commentsText = ex.getCommentsText();
                System.out.println(commentsText);
                buffer = ex.getText();
            }else if (path.endsWith(".docx")){   //读取文档后缀为.docx
                FileInputStream fs = new FileInputStream(new File(path));
                XWPFDocument xdoc = new XWPFDocument(fs);
                XWPFWordExtractor extractor = new XWPFWordExtractor(xdoc);
                buffer = extractor.getText();

            }else if (path.endsWith(".txt")){
                BufferedReader br = new BufferedReader(new FileReader(path));

                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                    buffer = line;
                }
                System.out.println(buffer);
                br.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return buffer;
    }

}
